package com.lmaos.allcontrol.beancontrol.class_;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class MySysClassLoader extends ClassLoader{
	private File classpath;
	public MySysClassLoader() {
	}
	
	 public MySysClassLoader(File classpath) {
		super();
		setClasspath(classpath);
	}

	public Class<?> myDefineClass(byte[] b, int off, int len)throws ClassFormatError{
		 return defineClass(null, b, off, len, null);
	 }
	 
	 public Class<?> myDefineClass(InputStream in, int off, int len)throws ClassFormatError{
		byte[] b = null;
		try {
			b = new byte[in.available()];
			in.read(b);
			return defineClass(null, b, off, len, null);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}finally{
			try {
				in.close();
			} catch (Exception e2) {
			}
		}
	 }
	 
	public void setClasspath(File classpath) {
		if(!classpath.exists()){
			classpath.mkdirs();
		}
		this.classpath = classpath;
	}
	public File getClasspath() {
		return classpath;
	}
	public File getClasspath(String name) {
		if(classpath!=null){
			if(name==null||name.isEmpty()||name.equals(".")){
				return classpath;
			}
			File resurceFile = new File(classpath, name);
			if(resurceFile.exists()){
				return resurceFile;
			}
		}
		return null;
	}
	@Override
	public URL getResource(String name) {
		try {
			File resurceFile = getClasspath(name);
			if(resurceFile!=null){
				return resurceFile.toURI().toURL();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.getResource(name);
	}
}
